package pCloud.transport;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import pCloud.service.ProtocolHandle;

/**
 * Implement the communication channel using socket.
 * 
 * This is used for both server (accepting connection and creating the
 * connection with the client) and client (normal connection that only does
 * sending and receiving).
 * 
 */
public class SocketTransportHandle implements TransportHandle {

	Socket commSocket = null;
	ObjectInputStream input;
	ObjectOutputStream output;

	public SocketTransportHandle(Socket comm)
			throws IOException {
		this.commSocket = comm;
		this.init();
	}

	@Override
	public void init() throws IOException {
		output = new ObjectOutputStream(commSocket.getOutputStream());
		input = new ObjectInputStream(commSocket.getInputStream());		
	}

	@Override
	public synchronized void send(Object m) throws IOException {
		output.writeObject(m);
	}

	@Override
	public Object receive() throws Exception {
		return input.readObject();
	}

	@Override
	public void close() {
		try {
			commSocket.close();
		} catch (Exception e) {
			System.err.println("Socket " + commSocket + "closed");
		}
	}

	public Socket getSocket() {
		return this.commSocket;
	}

	@Override
	public Object getLocalAddress() throws Exception {
		return this.commSocket.getLocalSocketAddress();
	}

	@Override
	public Object getRemoteAddress() throws Exception {
		return this.commSocket.getRemoteSocketAddress();
	}
}
